﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using System.Text;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class Market : PhoneApplicationPage
    {
        private static string key = "user";

        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        private Utente user;
        private string idcardtobuy;//usato per la query che acquista 
        private int pricecardtobuy;

        private Style containerStyle = Application.Current.Resources["MyCardCanvas"] as Style;
        private Style borderStyle = Application.Current.Resources["MyCardCardBorder"] as Style;
        private Style nameTextStyle = Application.Current.Resources["MyCardTextName"] as Style;
        private Style topTextStyle = Application.Current.Resources["MyCardTextTOP"] as Style;
        private Style bottomTextStyle = Application.Current.Resources["MyCardTextBOT"] as Style;
        private Style leftTextStyle = Application.Current.Resources["MyCardTextLEFT"] as Style;
        private Style rightTextStyle = Application.Current.Resources["MyCardTextRIGHT"] as Style;
        private Style levelTextStyle = Application.Current.Resources["MyCardTextLEVEL"] as Style;
        private Style priceTextStyle = Application.Current.Resources["MyCardTextPrice"] as Style;
        //private Style rarityTextStyle = Application.Current.Resources["MyCardTextRARITY"] as Style;
        private Style buyStyle = Application.Current.Resources["Remove"] as Style;

        public Market()
        {
            InitializeComponent();

            user = appSettings[key] as Utente;

            PointsText.Text = "You have " + user.getPoints().ToString() + " points";

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/getAllCards.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGetAllCards), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void buyButton_Tap(object sender, EventArgs e)
        {
            Button clicked = sender as Button;
            string price = clicked.Tag as string;
            if (Convert.ToInt32(price) > user.getPoints())
            {
                MessageBox.Show("You haven't enough points to buy this card");
            }
            else
            {
                idcardtobuy = clicked.Name;
                pricecardtobuy = Convert.ToInt32(price);

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/checkCard.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackCheckCard), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }

        private void GetRequestStreamCallbackGetAllCards(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackGetAllCards), myRequest);
        }//GetRequestStreamCallbackGetAllCards

        private void GetResponsetStreamCallbackGetAllCards(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingGetAllCards(result));
            }
        }//GetResponsetStreamCallbackGetAllCards

        private void ParsingGetAllCards(string result)
        {
            //controllo result
            if (result != "")//ho preferiti
            {
                //parsing e creo lista
                string[] ris = majorSplit(result);
                foreach (string record in ris)
                {
                    string[] dati = minorSplit(record);
                    string id = dati[0];
                    string name = dati[2];
                    string imageURL = dati[1];
                    string top = dati[3];
                    string bottom = dati[4];
                    string left = dati[5];
                    string right = dati[6];
                    string cost = dati[8];
                    string level = dati[7];

                    Canvas container = new Canvas();
                    container.Style = containerStyle;
                    var containerback = new ImageBrush();
                    Uri imageuricontainer = new Uri("img/buttonbg.png", UriKind.Relative);
                    containerback.ImageSource = new BitmapImage(imageuricontainer);
                    container.Background = containerback;

                    Border bord = new Border();
                    bord.Style = borderStyle;
                    var bordback = new ImageBrush();
                    Uri imageuribord = new Uri(imageURL, UriKind.Relative);
                    bordback.ImageSource = new BitmapImage(imageuribord);
                    bord.Background = bordback;

                    TextBlock nameText = new TextBlock();
                    nameText.Style = nameTextStyle;
                    nameText.Foreground = new SolidColorBrush(Colors.Black);
                    nameText.Text = name;

                    TextBlock topText = new TextBlock();
                    topText.Style = topTextStyle;
                    topText.Foreground = new SolidColorBrush(Colors.Black);
                    topText.Text = top;

                    TextBlock bottomText = new TextBlock();
                    bottomText.Style = bottomTextStyle;
                    bottomText.Foreground = new SolidColorBrush(Colors.Black);
                    bottomText.Text = bottom;

                    TextBlock leftText = new TextBlock();
                    leftText.Style = leftTextStyle;
                    leftText.Foreground = new SolidColorBrush(Colors.Black);
                    leftText.Text = left;

                    TextBlock rightText = new TextBlock();
                    rightText.Style = rightTextStyle;
                    rightText.Foreground = new SolidColorBrush(Colors.Black);
                    rightText.Text = right;

                    TextBlock priceText = new TextBlock();
                    priceText.Style = priceTextStyle;
                    priceText.Foreground = new SolidColorBrush(Colors.Black);
                    priceText.Text = cost;

                    TextBlock levelText = new TextBlock();
                    levelText.Style = levelTextStyle;
                    levelText.Foreground = new SolidColorBrush(Colors.Black);
                    levelText.Text = "Level: " + level;

                    /*TextBlock rarityText = new TextBlock();
                    rarityText.Style = rarityTextStyle;
                    rarityText.Foreground = new SolidColorBrush(Colors.Black);
                    rarityText.Text = "Rarity" + rarity;*/

                    Button buyButton = new Button();
                    buyButton.Style = buyStyle;
                    buyButton.Content = "Buy";
                    buyButton.Background = new SolidColorBrush(Color.FromArgb(255, 135, 0, 0));
                    Canvas.SetLeft(buyButton, 302);
                    Canvas.SetTop(buyButton, 118);
                    buyButton.Name = id;
                    buyButton.Tag = cost;
                    buyButton.Tap += new EventHandler<GestureEventArgs>(buyButton_Tap);

                    container.Children.Add(bord);
                    container.Children.Add(nameText);
                    container.Children.Add(topText);
                    container.Children.Add(bottomText);
                    container.Children.Add(leftText);
                    container.Children.Add(rightText);
                    container.Children.Add(priceText);
                    container.Children.Add(levelText);
                    //container.Children.Add(rarityText);
                    container.Children.Add(buyButton);

                    ContainerList.Items.Add(container);
                }
            }
        }//ParsingGetAllCards

        private void GetRequestStreamCallbackCheckCard(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&Iduser=" + user.getId().ToString() + "&Idcard=" + idcardtobuy;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackCheckCard), myRequest);
        }//GetRequestStreamCallbackCheckCard

        private void GetResponsetStreamCallbackCheckCard(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingCheckCard(result));
            }
        }//GetResponsetStreamCallbackCheckCard

        private void ParsingCheckCard(string result)
        {
            if (result == "") //è la prima carta di questo tipo che compro
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/insertInCarteUtente.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackInsertInCarteUtente), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
            else //avevo già una carta di queato tipo
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateQuantity.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateQuantity), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }//ParsingCheckCard

        private void GetRequestStreamCallbackInsertInCarteUtente(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&Iduser=" + user.getId().ToString() + "&Idcard=" + idcardtobuy;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackInsertInCarteUtente), myRequest);
        }//GetRequestStreamCallbackInsertInCarteUtente

        private void GetResponsetStreamCallbackInsertInCarteUtente(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingInsertInCarteUtente(result));
            }
        }//GetResponsetStreamCallbackInsertInCarteUtente

        private void ParsingInsertInCarteUtente(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                user.setPoints(user.getPoints() - pricecardtobuy);
                PointsText.Text = "You have " + user.getPoints().ToString() + " points";

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserPoints.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }//ParsingInsertInCarteUtente

        private void GetRequestStreamCallbackUpdateUserPoints(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + user.getId().ToString() + "&Points=" + user.getPoints().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackUpdateUserPoints), myRequest);
        }//GetRequestStreamCallbackUpdateUserPoints

        private void GetResponsetStreamCallbackUpdateUserPoints(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingUpdateUserPoints(result));
            }
        }//GetResponsetStreamCallbackUpdateUserPoints

        private void ParsingUpdateUserPoints(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                MessageBox.Show("Purchase complete!");
            }
        }//ParsingUpdateUserPoints

        private void GetRequestStreamCallbackUpdateQuantity(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&IdUser=" + user.getId().ToString() + "&IdCard=" + idcardtobuy ;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackUpdateQuantity), myRequest);
        }//GetRequestStreamCallbackUpdateQuantity

        private void GetResponsetStreamCallbackUpdateQuantity(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingUpdateQuantity(result));
            }
        }//GetResponsetStreamCallbackUpdateQuantity

        private void ParsingUpdateQuantity(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                user.setPoints(user.getPoints() - pricecardtobuy);
                PointsText.Text = "You have " + user.getPoints().ToString() + " points";

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserPoints.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }//ParsingUpdateQuantity

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}